<script lang="ts" setup>
  import autoScaling from '@/api/autoScaling'
  import lts from '@/api/lts'
  import { onMounted, reactive, ref, watch } from 'vue'
  import appStore from '@/store'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { useRouter, useRoute } from 'vue-router'
  import _ from 'lodash'
  const router = useRouter()
  const route = useRoute()
  interface optionList {
    value: string
    label: string
    disabled: boolean
  }
  const contentInfo: optionList[] = reactive([])
  const disabled = ref(false)
  const getData = () => {
    if (route.params.Tdata) {
      const str: string = decodeURIComponent(route.params.Tdata as string)
      contentInfo.push(...JSON.parse(str))
    }
    getFleetList()
  }
  let ltsData = reactive({
    data: {
      project_id: appStore.userStore.project_id,
      fleet_id: '',
      lts_config: {
        log_group_id: '',
        lts_access_config_name: '',
        lts_log_path: [''] as any
      },
      description: ''
    }
  })
  const LtsRef = ref<FormInstance>()
  const ListRef = ref<FormInstance>()
  const rules = reactive<FormRules>({
    fleet_id: [{ required: true, message: '请选择FleetID', trigger: 'blur' }],
    lts_access_config_name: [{ required: true, message: '请输入日志接入名称', trigger: 'blur' }],
    log_group_id: [{ required: true, message: '请输入日志组ID', trigger: 'blur' }],
    lts_log_path: [
      { required: true, message: '请输入路径', trigger: 'blur' },
      {
        pattern: /^\/([A-Za-z0-9_.-]\/?)+$/,
        message: '请输入正确的路径',
        trigger: 'blur'
      }
    ]
  })
  const olnyId = (rule: any, value: any, callback: any) => {
    let result = false
    listLtsLoGroup.forEach((item) => {
      if (item.label == value) {
        result = true
      }
    })
    if (value === '') {
      callback(new Error('日志组名称为空'))
    } else if (result) {
      callback(new Error('日志组名称重复'))
    } else {
      callback()
    }
  }
  const rulesId = reactive<FormRules>({
    log_group_name: [
      {
        required: true,
        trigger: 'blur',
        validator: olnyId
      }
    ],
    ttl_in_day: [{ required: true, type: 'number', min: 1, max: 365, message: '请输入大于等于1并小于等于365的数字', trigger: 'change' }]
  })
  const param = reactive({
    project_id: appStore.userStore.project_id,
    offset: 1,
    limit: 10,
    fleet_id: ''
  })
  let creating = ref(false)
  const onSubmit = async (formEl: FormInstance | undefined) => {
    if (creating.value) return
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let param
        param = JSON.parse(JSON.stringify(ltsData.data))
        try {
          creating.value = true
          let res = await lts.createLts(param)
          if (res.status < 300) {
            creating.value = false
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            localStorage.removeItem('ltsData')
            ElMessageBox.confirm('创建成功!是否继续创建日志转储？', '提示', {
              confirmButtonText: '是',
              cancelButtonText: '否',
              type: 'warning'
            })
              .then(async () => {
                router.push({
                  name: 'createTransfer',
                  params: {
                    idData: encodeURIComponent(JSON.stringify(res.data))
                  }
                })
              })
              .catch(() => {
                router.push({ name: 'ltsList' })
              })
          }
        } catch (err) {
          creating.value = false
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  const onReset = () => {
    ltsData.data = {
      project_id: appStore.userStore.project_id,
      fleet_id: '',
      lts_config: {
        log_group_id: '',
        lts_access_config_name: '',
        lts_log_path: [''] as any
      },
      description: ''
    }
  }
  watch(
    () => ltsData.data,
    (newValue, oldValue) => {
      localStorage.setItem('ltsData', JSON.stringify(newValue))
    },
    { deep: true }
  )
  const back = () => {
    router.go(-1)
  }
  onMounted(() => {
    getListLtsLoGroup()
    if (localStorage.getItem('ltsData')) {
      ltsData.data = JSON.parse(localStorage.getItem('ltsData') as string)
    }
  })
  const addPath = () => {
    let lastIndex = ltsData.data.lts_config.lts_log_path.length - 1
    if (!ltsData.data.lts_config.lts_log_path[lastIndex].length) {
      ElMessage({
        message: '请填写当前路径再新建',
        type: 'warning'
      })
      return false
    }
    ltsData.data.lts_config.lts_log_path.push('')
  }
  const deletePath = (index: any) => {
    if (index == 0) {
      ltsData.data.lts_config.lts_log_path[index] = ''
      return
    }
    ltsData.data.lts_config.lts_log_path.splice(index, 1)
  }
  const fleetOptions: optionList[] = reactive([])
  const getFleetList = async () => {
    let res = await autoScaling.getFleetList(param)
    if (!fleetOptions.length) {
      setFleetOptions(res.data.fleets)
    }
  }
  const listLtsLoGroup: optionList[] = reactive([])
  const getListLtsLoGroup = async () => {
    let res = await lts.getltsLogGroup(param)
    let arr = res.data.log_groups
    arr.forEach((item: any) => {
      listLtsLoGroup.push({
        label: item.log_group_name,
        value: `${item.log_group_id}`,
        disabled: false
      })
    })
  }
  const params = reactive({})
  const setFleetOptions = (arr: any) => {
    arr.forEach((item: any) => {
      const itemJson = contentInfo.find((task: any) => item.fleet_id === task.fleet_id)
      if (item.state === 'ACTIVE' && item.instance_type == 'VM') {
        fleetOptions.push({
          label: `${item.name}`,
          value: item.fleet_id,
          disabled: itemJson ? true : false
        })
      }
    })
  }
  const dialogFormVisible = ref(false)
  const formLabelWidth = '140px'
  const form = reactive({
    log_group_name: '',
    ttl_in_day: 7
  })
  const onSubmitList = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate(async (valid, fields) => {
      if (valid) {
        let param
        param = JSON.parse(JSON.stringify(form))
        try {
          let res = await lts.createltsLogGroup(param)
          if (res.status < 300) {
            ElMessage({
              message: '创建成功',
              type: 'success'
            })
            dialogFormVisible.value = false
            form.log_group_name = ''
            form.ttl_in_day = 7
            let obj = {
              label: res.data.log_group_name,
              value: `${res.data.log_group_id}`,
              disabled: false
            }
            listLtsLoGroup.push(obj)
            ltsData.data.lts_config.log_group_id = res.data.log_group_id
          }
        } catch (err) {
          ElMessage.error('创建失败')
        }
      } else {
        ElMessage({
          message: '请检查参数',
          type: 'warning'
        })
      }
    })
  }
  getData()
</script>
<template>
  <div id="createFleet">
    <div class="create-box">
      <span>新建日志</span>
      <span class="back return" v-if="appStore.userStore.project_id" @click="back">&lt;&nbsp;返回</span>
    </div>
    <div class="form-box">
      <el-form ref="LtsRef" :model="ltsData.data" label-width="140px" label-position="left" :inline="true" :rules="rules" class="ac-form">
        <div class="card-box">
          <div class="card-content">
            <el-form-item prop="fleet_id">
              <template #label>
                <div class="item-label">FleetID</div>
              </template>
              <el-select v-model="ltsData.data.fleet_id" class="m-2 fleet" placeholder="请选择fleet" :validate-event="true">
                <el-option v-for="item in fleetOptions" :key="item.value" :label="item.label" :value="item.value" :disabled="item.disabled">
                  <div class="fleetLabel">{{ item.label }}</div>
                  <div class="fleetValue">{{ item.value }}</div>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item prop="lts_config.lts_access_config_name" :rules="rules.lts_access_config_name">
              <template #label>
                <div class="item-label">日志接入名称</div>
              </template>
              <el-input v-model.trim="ltsData.data.lts_config.lts_access_config_name" maxlength="1024" />
            </el-form-item>
            <el-form-item prop="lts_config.log_group_id" :rules="rules.log_group_id">
              <template #label>
                <div class="item-label">日志组名称</div>
              </template>
              <el-select v-model="ltsData.data.lts_config.log_group_id" placeholder="请选择日志组名称" :validate-event="true" filterable>
                <el-option v-for="item in listLtsLoGroup" :key="item.value" :label="item.label" :value="item.value" />
              </el-select>
              <div class="icon-outbox">
                <div class="btn new" @click="dialogFormVisible = true">新建</div>
              </div>
            </el-form-item>
            <el-form-item>
              <template #label>
                <div class="item-label">描述</div>
              </template>
              <el-input v-model.trim="ltsData.data.description" maxlength="1024" placeholder="请输入描述" />
            </el-form-item>
            <div class="its_arr">
              <el-form-item
                :prop="'lts_config.lts_log_path.' + index"
                :rules="rules.lts_log_path"
                v-for="(item, index) in ltsData.data.lts_config.lts_log_path"
                :key="index"
              >
                <template #label>
                  <div class="item-label">
                    路径{{ index + 1 }}
                    <el-tooltip effect="dark" content="请输入正确的路径如:/root/log" placement="right"
                      ><el-icon><QuestionFilled /></el-icon
                    ></el-tooltip>
                  </div>
                </template>
                <div class="its_item">
                  <div>
                    <el-input v-model.trim="ltsData.data.lts_config.lts_log_path[index]" maxlength="1024" placeholder="请输入正确的路径如:/root/log" />
                  </div>
                  <div class="icon-outbox">
                    <div class="icon-box" v-if="index == 0">
                      <el-icon @click="addPath"><component is="Plus" /></el-icon>
                    </div>
                    <div class="icon-box">
                      <el-icon><component is="Delete" @click="deletePath(index)" /></el-icon>
                    </div>
                  </div>
                </div>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>
      <div class="operateButton">
        <el-button class="btn button" @click="onReset">重置</el-button>
        <el-button class="btn new button" type="primary" @click="onSubmit(LtsRef)">创建</el-button>
      </div>
    </div>
    <el-dialog v-model="dialogFormVisible" title="添加日志组id" width="22%">
      <el-form :model="form" :rules="rulesId" ref="ListRef">
        <el-form-item label="日志组名称" :label-width="formLabelWidth" prop="log_group_name">
          <el-input v-model.trim="form.log_group_name" autocomplete="off" placeholder="请输入日志组名称" />
        </el-form-item>
        <el-form-item label="日志保留时间(天)" :label-width="formLabelWidth" prop="ttl_in_day">
          <el-input v-model.number="form.ttl_in_day" autocomplete="off" placeholder="请输入日志保留时间" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button class="btn button" @click="dialogFormVisible = false">取消</el-button>
          <el-button class="btn new button" type="primary" @click="onSubmitList(ListRef)"> 创建 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" scoped>
  @import '@/assets/scss/dropdownBox.scss';
  #createFleet {
    background-color: $blank-color;
    .dialog-footer {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .its_arr {
      display: flex;
      flex-direction: column;
      .its_item {
        display: flex;
        align-items: center;
      }
    }
    .its_arr:not(:last-child) {
      margin-bottom: 10px;
    }
    .icon-outbox {
      display: flex;
      .btn {
        width: 50px;
        height: 28px;
        margin-left: 10px;
      }
    }
    .icon-box {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 28px;
      height: 28px;
      border: 1px solid $border-color;
      margin-left: 10px;
      cursor: pointer;
      .el-icon {
        margin-left: 0px;
        color: #1d1d1f;
      }
    }
    .create-box {
      height: 60px;
      width: calc(100% - 200px);
      position: absolute;
      top: 50px;
      left: 200px;
      background-color: $blank-color;
      color: $text-color;
      display: flex;
      align-items: center;
      z-index: 1;
      span {
        font-size: 16px;
        font-weight: bold;
        margin-left: 20px;
        margin-right: 10px;
        line-height: 60px;
      }
      .button {
        width: 100px;
        height: 28px;
      }
      .return {
        font-size: 14px;
        margin-left: 0px;
      }
    }
    .form-box {
      background-color: $blank-color;
      padding: 30px;
      margin-top: 60px;
      .select-box {
        display: flex;
        align-items: center;
        margin-bottom: 30px;
        .select-lable {
          width: 165px;
          color: $text-color;
          font-size: 14px;
          .must {
            color: rgb(245, 108, 108);
            margin-right: 4px;
          }
        }
      }
      .card-box {
        background-color: $blank-color;
        margin-bottom: 36px;
        .card-header {
          display: flex;
          align-items: center;
          height: 14px;
          margin-bottom: 44px;

          .header-bar {
            height: 100%;
            width: 4px;
            background: $main-color;
            margin-right: 6px;
          }
          .header-title {
            height: 100%;
            line-height: 100%;
            color: #1d1d1f;
            font-weight: bold;
            font-size: 14px;
            margin-right: 10px;
          }
        }
      }
      .el-form-item {
        width: 50%;
        margin: 0;
        margin-bottom: 30px;

        :deep(.el-form-item__label) {
          width: 165px !important;
        }
        .item-label {
          width: 180px;
          color: $text-color;
          display: flex;
          align-items: center;
          i {
            margin-left: 20px;
          }
        }

        .el-input {
          width: 480px;
          height: 30px;
        }
        .el-select {
          width: 480px;
          height: 30px;
          line-height: 30px;
          :deep(.el-input) {
            height: 30px;
            .el-input__inner {
              height: 30px;
            }
          }
        }
      }
    }
    .operateButton {
      justify-content: center;
      display: flex;
      gap: 20px;
      margin-top: 30px;
      .el-form-item {
        width: 260px;
      }
      .button {
        width: 120px;
        height: 34px;
      }
    }
  }
</style>
